package com.mai.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.mai.demo.entity.dto.ExcelConvertDTO;
import com.mai.demo.service.ExcelConvertService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;


/**
 * todo 白写半天，需求理解错了 ，这项目就是用来处理这拖狗屎的 文件不是用户上传的 是死的放在程序里的
 *
 * @className: BaseController
 * @author: Wang
 * @date: 2024/12/23 上午10:09
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping
@RequiredArgsConstructor
public class BaseController {


    private final ExcelConvertService convertService;


    /**
     * 健康检查
     *
     * @return ok
     */
    @GetMapping("/ok")
    public String health() {
        return "ok";
    }
    @PostMapping("/convert")
    public void convert(ExcelConvertDTO dto,HttpServletResponse response) {
        // 校验数据
        validData(dto);

        try {
            convertService.convert(dto.getFile(),dto.getStartColumn(), dto.getEndColumn(),dto.getStartRow(), dto.getEndRow(),response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("转换失败");
        }
    }


    private void validData(ExcelConvertDTO dto) {
        String originalFilename = dto.getFile().getOriginalFilename();
        // 校验是否是excel文件
        if (StrUtil.isBlank(originalFilename) || (!originalFilename.endsWith(".xlsx") && !originalFilename.endsWith(".xls"))) {
            throw new RuntimeException("请上传excel文件");
        }
        int startRow =dto.getStartRow();
        int endRow = dto.getEndRow();
        if (startRow > endRow) {
            throw new RuntimeException("起始行不得大于结束行");
        }
        if (dto.getStartColumn() > dto.getEndColumn()){
            throw new RuntimeException("起始列不得大于结束列");
        }

    }
}
